package com.rtx.express.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.lop.open.api.sdk.DefaultDomainApiClient;
import com.lop.open.api.sdk.domain.ElectronicSingleSurface.WaybillReceiveApi.receiveWaybillByJos.WaybillAddress;
import com.lop.open.api.sdk.domain.ElectronicSingleSurface.WaybillReceiveApi.receiveWaybillByJos.WaybillDTO;
import com.lop.open.api.sdk.domain.jdcloudprint.PullDataService.pullData.PullDataReqDTO;
import com.lop.open.api.sdk.domain.jdcloudprint.PullDataService.pullData.WayBillInfo;
import com.lop.open.api.sdk.plugin.LopPlugin;
import com.lop.open.api.sdk.plugin.factory.OAuth2PluginFactory;
import com.lop.open.api.sdk.request.ElectronicSingleSurface.OrderCreateLopRequest;
import com.lop.open.api.sdk.request.jdcloudprint.PullDataServicePullDataLopRequest;
import com.lop.open.api.sdk.response.ElectronicSingleSurface.OrderCreateLopResponse;
import com.lop.open.api.sdk.response.jdcloudprint.PullDataServicePullDataLopResponse;
import com.rtx.api.annotation.RtxExpressApi;
//import com.lop.open.api.sdk.response.jdcloudprint.*;
import com.rtx.edi.model.express.bo.ExpressBO;
import com.rtx.edi.model.express.po.PlExpressApi;
import com.rtx.edi.model.express.po.PlExpressApiConfig;
import com.rtx.edi.model.express.po.PlExpressResult;
import com.rtx.express.service.IExpressService;

@RtxExpressApi(expressApiName = "京东无界")
@SuppressWarnings("all")
@Service("快递接口JDWJ")
public class JdwjExpressAPI implements IExpressService{
	
	Logger log = LoggerFactory.getLogger(this.getClass());
	
	protected String server_url="https://api.jdl.cn";
	private static String appKey="3ffd9a0cef9d4a008e253fbd1a3d1d95";
	private static String appSecret="37ed7fa678984587b4eae1bae76f490a";
	private static String refreshToken="d188697888504c32b2a4000739815b73";//迪克斯
	private static String vendorId="621426";//迪克斯
	private static String settlementCode="";//承运商商家结算编码
	//迪克斯授权令牌{"accessExpire":"2024-06-08 15:23:59","accessToken":"d904fecfe0da47379328bc08b2fbdd7a","clientId":"3ffd9a0cef9d4a008e253fbd1a3d1d95","code":"f2840c7b41574bf6af79297eea519d20","refreshExpire":"2024-06-08 15:23:59","refreshToken":"d188697888504c32b2a4000739815b73","sellerId":"dickies-小严"}
	//店铺ID：12971487  店铺名称：斯凯奇利发专卖店
	//利发授权令牌{"accessExpire":"2024-08-14 15:40:08","accessToken":"14f6028a8562434581ab16fc072f90e1","clientId":"3ffd9a0cef9d4a008e253fbd1a3d1d95","code":"358e62448e85488187476792c34938b5","refreshExpire":"2024-08-14 15:40:08","refreshToken":"c38a838d6541429ca84f91b3627a730f","sellerId":"斯凯奇利发专卖店"}

	@Override
	public void callCreaterOrderAPI(ExpressBO bo) {
		PlExpressApi task =  bo.getExpressTask();
		PlExpressApiConfig config = bo.getExpressConfig();
		try {
			mappingConfig(config);
			
			String uid = UUID.randomUUID().toString();
            DefaultDomainApiClient client = new DefaultDomainApiClient(server_url);
            LopPlugin oauthPlugin = OAuth2PluginFactory.produceLopPlugin(client.getServerUrl(), appKey, appSecret, config.getRefreshtoken());
            
            //映射 无界电子面单【ISV】下单接口 请求
            OrderCreateLopRequest wayBilRequest = mappingCreateOrderDTO(bo,oauthPlugin);
            
            //请求无界电子面单下单接口
            log.info("uid-{}-单号-{}-京东无界电子面单请求-{}",uid,task.getExternorderkey(),JSON.toJSONString(wayBilRequest));
            OrderCreateLopResponse wayBilResponse = client.execute(wayBilRequest);
            log.info("uid-{}-单号-{}-京东无界电子面单响应-{}",uid,task.getExternorderkey(),JSON.toJSONString(wayBilResponse));
            
            if(0!=wayBilResponse.getResult().getStatusCode()) {
            	throw new RuntimeException("京东无界下单接口响应-"+JSON.toJSONString(wayBilResponse));
            }
            
        	String billno = wayBilResponse.getResult().getData().getWaybillCodeList().get(0);
        	String orderNo = wayBilResponse.getResult().getData().getPlatformOrderNo();
            
            
        	//映射 打印数据 (pullData) 请求
        	PullDataServicePullDataLopRequest printRequest = mappingPritRequest(billno,orderNo,bo,oauthPlugin);
        	//请求无界电子面单下单接口
        	log.info("uid-{}-单号-{}-京东打印数据请求-{}",uid,task.getExternorderkey(),JSON.toJSONString(printRequest));
        	PullDataServicePullDataLopResponse printResponse = client.execute(printRequest);
        	log.info("uid-{}-单号-{}-京东打印数据响应-{}",uid,task.getExternorderkey(),JSON.toJSONString(printResponse));
        	
        	if(!"1".equals(printResponse.getResult().getCode())) {
            	throw new RuntimeException("打印数据获取接口响应-"+JSON.toJSONString(printResponse));
        	}

        	String printData = printResponse.getResult().getPrePrintDatas().get(0).getPerPrintData();
        	String wayBillNo = printResponse.getResult().getPrePrintDatas().get(0).getWayBillNo();
        	
        	bo.setCallCreateOrderAPIResult("ok");
			PlExpressResult expressResult = bo.getExpressResultFillSendAndReceiver();
			expressResult.setExternorderkey(task.getExternorderkey());
			expressResult.setWaybillNo(wayBillNo);
			expressResult.setPrintData(printData);
			bo.setExpressResult(expressResult);

		} catch (Exception e) {
			log.error("",e);
			bo.setMsg("订单-"+task.getExternorderkey()+"-获取京东云打印数据失败：" + e.getMessage());
		}
	}

	private void mappingConfig(PlExpressApiConfig config) {
		if(!StringUtils.hasLength(config.getRefreshtoken())) {
			config.setRefreshtoken(refreshToken);
		}
		if(!StringUtils.hasLength(config.getVendorId())) {
			config.setVendorId(vendorId);
		}
	}
	
	/**
	 * 无界电子面单【ISV】下单接口
	 * https://cloud.jdl.com/#/open-business-document/api-doc/207/464
	 * @return
	 */
	private OrderCreateLopRequest mappingCreateOrderDTO(ExpressBO bo,LopPlugin oauthPlugin) {
		PlExpressApi task = bo.getExpressTask();
		PlExpressApiConfig config = bo.getExpressConfig();
		
		OrderCreateLopRequest request = new OrderCreateLopRequest();
		
        WaybillDTO waybillDTO = new WaybillDTO();

        WaybillAddress fromAddress = new WaybillAddress();
        fromAddress.setMobile(task.getSendMobile());
        fromAddress.setPhone(task.getSendPhone());
        fromAddress.setContact(task.getSendName());
        fromAddress.setAddress(task.getSendAddress());
        waybillDTO.setFromAddress(fromAddress);

        WaybillAddress toAddress = new WaybillAddress();
        toAddress.setMobile(task.getReceiverMobile());
        toAddress.setPhone(task.getReceiverPhone());
        toAddress.setContact(task.getReceiverName());
        toAddress.setAddress(task.getReceiverAddress());
//        toAddress.setAddress("收货地址");
        toAddress.setProvinceName(task.getReceiverProvince());
        toAddress.setCityName(task.getReceiverCity());
        toAddress.setCountryName(task.getReceiverCounty());
        waybillDTO.setToAddress(toAddress);


        waybillDTO.setRemark("");
        waybillDTO.setExtendField1("扩展字段1");
        waybillDTO.setExtendField2("扩展字段2");
        waybillDTO.setExtendField3("扩展字段3");

        waybillDTO.setWaybillType(Integer.valueOf(1));
        waybillDTO.setWaybillCount(Integer.valueOf(1));

        waybillDTO.setPlatformOrderNo(task.getTid());
        waybillDTO.setVendorCode(config.getVendorId());
//        waybillDTO.setVendorCode("621426");
//        waybillDTO.setVendorName("DICKIES童装旗舰店");
//        waybillDTO.setBranchCode("52936");
//        waybillDTO.setVendorName("HushPuppies官方旗舰店");
//        waybillDTO.setVendorCode("595170");
        
        waybillDTO.setVendorCode(config.getVendorId());
        waybillDTO.setVendorName(config.getJdvendorName());
        waybillDTO.setBranchCode(config.getJdbrandcode());
        
        waybillDTO.setVendorOrderCode(task.getExternorderkey());
        waybillDTO.setSalePlatform("0010001");
        waybillDTO.setWeight(new BigDecimal(0));
        waybillDTO.setVolume(new BigDecimal(0));
        waybillDTO.setPayType(Integer.valueOf(0));
        waybillDTO.setShouldPayMoney(new BigDecimal(0));
        waybillDTO.setNeedGuarantee(Boolean.valueOf(true));
        waybillDTO.setGuaranteeMoney(new BigDecimal(0));
        waybillDTO.setExpressPayMethod("1");
        waybillDTO.setExpressType(config.getExpressType());
        
        waybillDTO.setSettlementCode(config.getSettlementCode());//商家结算编码 直营承运商必填,长度1~50
        waybillDTO.setProviderCode(config.getPlatformCarriercode());//承运商编码（与providerId必填一个），字段长度1~32
//        waybillDTO.setExpressType(task.getExpressType());//快件产品类别 目前顺丰使用，后续可根据承运商自己定义 1:顺丰次日 2:顺丰隔日，下单时商家选择产品类别，长度1

        request.setWaybillDTO(waybillDTO);
        request.setAppKey(appKey);
        
        request.addLopPlugin(oauthPlugin);
		return request;
	}
	


	/**
	 * 获取打印数据 (pullData)
	 * https://cloud.jdl.com/#/open-business-document/api-doc/157/191
	 */
	public PullDataServicePullDataLopRequest mappingPritRequest(String billno,String orderNo,ExpressBO bo,LopPlugin oauthPlugin) {
		PlExpressApi task = bo.getExpressTask();
		PlExpressApiConfig config = bo.getExpressConfig();
		
		PullDataServicePullDataLopRequest request = new PullDataServicePullDataLopRequest();
		PullDataReqDTO pullDataReqDTO = new  PullDataReqDTO();
		pullDataReqDTO.setCpCode(config.getPlatformCarriercode());
		pullDataReqDTO.setObjectId(UUID.randomUUID().toString());
		Map parameters = new HashMap();
//		parameters.put("ewCustomerCode", config.getEwCustomerCode());//迪克斯商家id 621426
//		parameters.put("ewCustomerCode", "621426");//迪克斯商家id 621426
		parameters.put("eCustomerCode", config.getVendorId());//
		pullDataReqDTO.setParameters(parameters);

		List<WayBillInfo> wayBillInfos = new ArrayList<>();
		WayBillInfo wayBillInfo = new WayBillInfo();
		wayBillInfo.setOrderNo(orderNo);
		wayBillInfo.setWayBillCode(billno);
		wayBillInfo.setPopFlag(0);
		wayBillInfos.add(wayBillInfo);
		pullDataReqDTO.setWayBillInfos(wayBillInfos);
		request.setPullDataReqDTO(pullDataReqDTO);

		request.addLopPlugin(oauthPlugin);
		return request;
//		log.info("获取京东云打印请求:"+JSON.toJSONString(request));
//		response = client.execute(request);
//		log.info("获取京东云打印结果:"+JSON.toJSONString(response));
//		expressResponse.setPrintData(response.getResult().getPrePrintDatas().get(0).getPerPrintData());
//		if(!"0".equals(String.valueOf(response.getCode()))) {
//			throw new RuntimeException(response.getMsg());
//		}
//		if(StringUtils.isEmpty(expressResponse.getPrintData())) {
//			throw new RuntimeException("获取京东云打印数据失败");
//		}
	}
	
	@Override
	public void handleCreaterOrderAPIResponse(ExpressBO bo) {
		// TODO Auto-generated method stub
		
	}

}
